"""辅助功能函数模块，仅调用 core_utils.py 的核心函数。"""

from src.core_utils import (
    load_field_stats, load_and_filter_city, get_missing_and_unique_stats,
    get_mean_table, print_mean_table, get_box_stats, print_box_stats,
    anova_by_year, print_anova_results
)
from src.core_utils import plot_radar_chart  # 添加此行以导入 plot_radar_chart
import pandas as pd
from tabulate import tabulate

def aux_des_workflow(config):
    """
    一站式辅助函数，调用 core_utils 完成 des.py 的主要分析流程。
    参数 config: dict，包含所有路径和字段设置。
    """
    # 数据加载与预处理
    field_stats = load_field_stats(config.get('json_path'))
    city_df = load_and_filter_city(config.get('csv_path'))
    if city_df is None:
        return
    missing_rate, unique_counts = get_missing_and_unique_stats(city_df)
    print("\n【缺失率前10的字段及示例值】")
    top_missing = missing_rate.sort_values(ascending=False)[:10]
    for col in top_missing.index:
        example = field_stats.get(col, {}).get("示例值", [])
        print(f"{col}: 缺失率 {top_missing[col]:.2%}, 示例值: {example}")
    print("\n【唯一值极少（<=5）或极多（>1000）的字段】")
    for col in city_df.columns:
        n = unique_counts[col]
        if n <= 5 or n > 1000:
            print(f"{col}: 唯一值数量 {n}, 示例值: {field_stats.get(col, {}).get('示例值', [])}")

    # 描述性统计与可视化
    score_fields = config.get('score_fields')
    year_field = config.get('year_field')
    mean_table = get_mean_table(city_df, score_fields, year_field)
    print_mean_table(mean_table)
    years = sorted(mean_table.index)
    radar_path = f"{config.get('figures_dir', 'figures')}/三年四项得分雷达图.png"
    plot_radar_chart(mean_table, score_fields, years, save_path=radar_path)
    print(f"雷达图已保存：{radar_path}")
    box_stats = get_box_stats(city_df, score_fields, year_field)
    print_box_stats(box_stats)

    # 方差分析（ANOVA）
    anova_results = anova_by_year(city_df, score_fields, year_field)
    print_anova_results(anova_results)

    # 分组对比分析
    if "性别" in city_df.columns:
        print("\n【按性别分组的均值（各年份）】")
        group_table = city_df.groupby([year_field, "性别"])[score_fields].mean()
        print(tabulate(group_table, headers='keys', tablefmt='github', floatfmt=".2f"))
    if "出生队列分组" in city_df.columns:
        print("\n【cohort（出生队列分组）描述性统计】")
        cohort_field = "出生队列分组"
        cohort_mean = city_df.groupby(cohort_field)[score_fields].mean()
        print(tabulate(cohort_mean, headers='keys', tablefmt='github', floatfmt=".2f"))

